package org.cfx.gift.controller;

import org.cfx.gift.exception.code.ResponseCode;
import org.cfx.gift.util.AjaxResult;
import org.cfx.gift.util.FastdfsUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

/**
 * @author RTX 9090
 */
@RestController
@RequestMapping("/common")
public class CommonController {

//    @Value("${fastdfs.url}")
//    private String url;

    @PostMapping("/fastDfs/upload")
    public AjaxResult upload(MultipartFile file) {

        try {
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String extName = originalFilename.substring(originalFilename.indexOf(".") + 1, originalFilename.length());
            String upload = FastdfsUtil.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(upload);
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage("请重新选择图片上传");
        }
    }

    @DeleteMapping("/fastDfs/delete")
    public AjaxResult delete(@RequestBody Map<String,String> filePath) {
        if (filePath.get("path").startsWith("http://")){
            String substring = filePath.get("path").substring(filePath.get("path").indexOf("8") + 4, filePath.get("path").length());
            filePath.put("path",substring);
        }
        System.out.println(filePath);
        boolean path = FastdfsUtil.delete(filePath.get("path"));

        if (path) {
            return AjaxResult.me().setResultObj(path);
        }else {
            return AjaxResult.me().setCode(ResponseCode.RESPONSE_CODE_500.getCode());
        }
    }
}
